import os
from logging import handlers

import wx
import string
import logging


class CharValidator(wx.PyValidator):
    def __init__(self, flag):
        wx.PyValidator.__init__(self)
        self.flag = flag
        self.Bind(wx.EVT_CHAR, self.OnChar)

    def Clone(self):
        """
        Note that every validator must implement the Clone() method.
        """
        return CharValidator(self.flag)

    def Validate(self, win):
        return True

    def TransferToWindow(self):
        return True

    def TransferFromWindow(self):
        return True

    def OnChar(self, evt):
        key = chr(evt.GetKeyCode())
        if self.flag == "only-digit" and key not in string.digits:
            return
        if self.flag == "no-alpha" and key in string.letters:
            return
        if self.flag == "no-digit" and key in string.digits:
            return
        evt.Skip()


class LogManager:
    def __init__(self, issave=True):
        self.__save = issave
        self.logdir = ".\log"
        self.mkdir(self.logdir)
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        fh = handlers.TimedRotatingFileHandler(filename=self.logdir + os.sep + 'assistant_iic.log', when='M', backupCount=1,
                                               encoding="utf-8")
        fh.setFormatter(logging.Formatter("[%(asctime)s]:%(levelname)s:%(message)s"))
        self.logger.addHandler(fh)

    def mkdir(self, path):
        # self.print('创建数据保存文件夹')
        path = path.strip()
        path = path.rstrip("\\")
        isExists = os.path.exists(path)
        if not isExists:
            os.makedirs(path)
            self.print(path + ' 创建成功')  # ' 创建成功'
            return True
        else:
            pass
            # 如果目录存在则不创建，并提示目录已存在
            # self.print(path + ' 目录已存在')

    def print(self, *msg, needsave=True, level="i"):
        pass
        print(*msg) # 元组解包
        if self.__save and needsave:
            self.__saveLog(msg=msg, level=level)

    def __saveLog(self, msg, level="i"):
        # 创建一个logger
        if level == "e":
            self.logger.error(msg)
        else:
            self.logger.info(msg)


# class EasyHttp:
#     def __init__(self):
#         print()
#     def request(self,url,method):
logMgr = LogManager()
import abc


class IicCallback(metaclass=abc.ABCMeta):
    @classmethod
    def onUSBConnectd(self):
        pass

    def onUSBClosed(self):
        pass

    def onDevInit(self):
        pass

    def onReceived(self, respData):
        pass

    def onStateOutput(self, level="i", msg="", errorCode=-1):
        pass




def bytes2Hex(bytes):
    l = [hex(int(i) & 0xff) for i in bytes]
    return " ".join(l)


def findAddrKey(dict, val):
    for (k, v) in dict.items():
        if v.addr == val:
            return k
    return None


def dictContains(dict, key):
    for k in dict.keys():
        if k == key:
            return True
    return False


